package org.example.innovate.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class OssUpload {
    public static String publishImgToOSS(MultipartFile file, String dataPath) {
        // 工具类取值
        String endPoint = OSSClientUtil.getEndPoint();
        String accessKeyId = OSSClientUtil.getAccessKeyId();
        String accessKeySecret = OSSClientUtil.getAccessKeySecret();
        String bucketName = OSSClientUtil.getBucketName();
        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            // 获取文件名称
            String fileName = file.getOriginalFilename();
            // 3 拼接
            fileName = dataPath;
            // 4 调用oss方法实现上传
            ossClient.putObject(bucketName, fileName, inputStream);
            // 5 关闭ossClient
            ossClient.shutdown();
            // 把上传之后的文件路径返回  需要符合阿里云oss的上传路径
            // https://nsx-fitness.oss-cn-guangzhou.aliyuncs.com/..
            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void load(String filePath, String objectName) throws IOException {
        String endPoint = OSSClientUtil.getEndPoint();
        String accessKeyId = OSSClientUtil.getAccessKeyId();
        String accessKeySecret = OSSClientUtil.getAccessKeySecret();
        String bucketName = OSSClientUtil.getBucketName();
        File file = new File(filePath);

        if (!file.exists() || file.isDirectory()) {
            throw new IOException("Invalid file path: " + filePath);
        }

        // 创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        try (FileInputStream fis = new FileInputStream(file)) {
            // 上传文件
            ossClient.putObject(bucketName, objectName, fis);
            System.out.println("File uploaded to OSS successfully.");
        } finally {
            // 关闭OSS客户端
            ossClient.shutdown();
        }
    }
}
